package com.aiti.lulian.service.newCard;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.newCard.CardAdminListFieldConfigDto;
import com.aiti.lulian.entity.newCard.CardAdminListFieldConfig;
import com.aiti.lulian.mapper.newCard.CardAdminListFieldConfigMapper;
import com.aiti.lulian.service.CardAdminListFieldConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CardAdminListFieldConfigServiceImpl extends ServiceImpl<CardAdminListFieldConfigMapper, CardAdminListFieldConfig> implements CardAdminListFieldConfigService {

    @Autowired
    private CardAdminListFieldConfigMapper cardAdminListFieldConfigMapper;

    @Override
    public Message getListFieldByUserId(String userId) {
        // 先查询当前用户是否有自定义配置，若没有则返回系统默认配置
        List<CardAdminListFieldConfig> fieldConfigs = cardAdminListFieldConfigMapper.selectList(new LambdaQueryWrapper<CardAdminListFieldConfig>().eq(CardAdminListFieldConfig::getCreator, userId).orderByAsc(CardAdminListFieldConfig::getSort));
        if (fieldConfigs.isEmpty()) {
            // 返回系统默认配置
            List<CardAdminListFieldConfig> defaultFieldConfigList = cardAdminListFieldConfigMapper.selectList(new LambdaQueryWrapper<CardAdminListFieldConfig>().eq(CardAdminListFieldConfig::getCreator, "1").orderByAsc(CardAdminListFieldConfig::getSort));
            List<CardAdminListFieldConfig> defaultFieldConfigs = defaultFieldConfigList.stream().peek(i -> i.setBaseId(null)).collect(Collectors.toList());
            return Message.success(defaultFieldConfigs);
        }
        return Message.success(fieldConfigs);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Message configListField(CardAdminListFieldConfigDto dto) {
        List<CardAdminListFieldConfig> params = dto.getDataList();
        if (params != null && !params.isEmpty()) {
            if (StrUtil.isBlank(params.get(0).getBaseId())) {
                // 保存一份属于该用户的配置数据
                params.forEach(i -> i.setBaseId(IdUtil.simpleUUID()).setCreator(dto.getUserId()).setBaseCreateTime(new Date()).setBaseUpdateTime(new Date()));
                this.saveBatch(params);
            } else {
                params.forEach(i -> i.setBaseUpdateTime(new Date()));
                this.updateBatchById(params);
            }
        }
        return Message.success("配置成功");
    }
}
